#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import os

from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp import template

class Rudeness(db.Model):
    creator = db.UserProperty()
    body = db.StringProperty(indexed=False)
    use_count = db.IntegerProperty(default=0)

class Use(db.Model):
    user = db.UserProperty()
    rudeness_body = db.StringProperty(indexed=False)
    timestamp = db.DateTimeProperty(auto_now_add=True)
    rudeness = db.ReferenceProperty(Rudeness)


# Main handler - shows rude responses sorted by usage
class MainHandler(webapp.RequestHandler):
    def get(self):
        """ 
        Shows recent Rude Responses sorted by use count
        """
        query = Rudeness.all()
        query.order("-use_count")
        rudenesses = query.fetch(50)

        template_values = { "rudenesses" : rudenesses }
        path = os.path.join(os.path.dirname(__file__), 'templates/index.html')
        self.response.out.write(template.render(path, template_values))


class CreateRudenessHandler(webapp.RequestHandler):
    def post(self):
        """
        Allows users to create a new Rude Response
        """
        user = users.get_current_user()

        body = self.request.get("body")
        rudeness = Rudeness(
                body=self.request.get("body"),
                creator=user
                )
        rudeness.put()
        self.redirect("/")


class UseRudenessHandler(webapp.RequestHandler):
    def post(self):
        """
        Counts the use of a Rude Response, creates a new
        'Used' item in the datastore
        """
        user = users.get_current_user()

        rudeness = db.get(self.request.get("key"))
        use = Use(user=user, 
                  rudeness=rudeness,
                  rudeness_body=rudeness.body)
        use.put()

        # Now let's increment the use count:
        rudeness.use_count = rudeness.use_count + 1
        rudeness.put()

        self.redirect("/recent")

class RecentRudenessHandler(webapp.RequestHandler):
    def get(self):
        """
        Shows a user the recent responses used
        """
        user = users.get_current_user()

        query = Use.all()
        query.filter("user =", user)
        query.order("-timestamp")
        uses = query.fetch(50)

        template_values = { "uses" : uses }
        path = os.path.join(os.path.dirname(__file__), 'templates/recent.html')
        self.response.out.write(template.render(path, template_values))

mappings = [
    ("/", MainHandler),
    ("/create", CreateRudenessHandler),
    ("/use", UseRudenessHandler),
    ("/recent", RecentRudenessHandler)
]

def main():
    application = webapp.WSGIApplication(mappings,
                                         debug=True)
    util.run_wsgi_app(application)


if __name__ == '__main__':
    main()
